package com.deep.seata.service.impl;

import com.deep.seata.dao.StorageDao;
import com.deep.seata.service.TccActionTwo;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
public class TccActionTwoImpl implements TccActionTwo {

    private final static Logger LOGGER = LoggerFactory.getLogger(TccActionTwoImpl.class);

    @Autowired
    private StorageDao storageDao;

    @Override
    public boolean storageReducePrepare(BusinessActionContext actionContext, long productId, int count, boolean flag) {
        if (null == actionContext) {
            return false;
        }
        String xid = actionContext.getXid();
        LOGGER.info("TccActionTwo storageReducePrepare, xid:" + xid);
        storageDao.fozen(productId, count);
        LOGGER.info(actionContext.toString());
        if (flag) {
            throw new RuntimeException("测试异常");
        }
        return true;
    }

    @Override
    public boolean storageReduceCommit(BusinessActionContext actionContext) {
        String xid = actionContext.getXid();
        LOGGER.info("TccActionTwo storageReduceCommit, xid:" + xid);
        LOGGER.info(actionContext.toString());
        long productId = Long.valueOf(actionContext.getActionContext("productId").toString());
        int count = Integer.valueOf(actionContext.getActionContext("count").toString());
        boolean flag = Boolean.valueOf((Boolean) actionContext.getActionContext("flag")).booleanValue();

        LOGGER.info("productId = {}", productId);
        LOGGER.info("count = {}", count);
        LOGGER.info("flag = {}", flag);

        storageDao.reduce(productId, count);
        return true;
    }

    @Override
    public boolean storageReduceRollback(BusinessActionContext actionContext) {
        String xid = actionContext.getXid();
        LOGGER.info("TccActionTwo storageReduceRollback, xid:" + xid);
        long productId = Long.valueOf(actionContext.getActionContext("productId").toString());
        int count = Integer.valueOf(actionContext.getActionContext("count").toString());
        boolean flag = Boolean.valueOf((Boolean) actionContext.getActionContext("flag")).booleanValue();

        LOGGER.info("productId = {}", productId);
        LOGGER.info("count = {}", count);
        LOGGER.info("flag = {}", flag);

        storageDao.rollback(productId, count);
        return true;
    }

}
